Rows: 19,025
Columns: 17
$ cntry             <chr> "AT", "AT", "AT", "AT", "AT", "AT", "AT", "AT", "AT"…
$ ccnthum           <chr> "Principalmente humano", "Igualmente natural y human…
$ ccrdprs           <chr> "4", "Mucho", "8", "6", "Mucho", "8", "7", "8", "2",…
$ wrclmch           <chr> "Muy preocupado", "Extremadamente preocupado", "Extr…
$ gndr              <fct> Hombre, Mujer, Mujer, Mujer, Hombre, Mujer, Mujer, M…
$ agea              <dbl> 65, 21, 53, 78, 64, 59, 77, 52, 75, 44, 49, 63, 76, …
$ eisced            <chr> "Secundaria alta alta", "Terciaria baja", "Terciaria…
$ impricha          <chr> "No parecido a mi", "Un poco parecido a mi", "Un poc…
$ ipeqopta          <chr> "Parecido a mi", "Parecido a mi", "Muy parecido a mi…
$ ipmodsta          <chr> "Parecido a mi", "Parecido a mi", "Algo parecido a m…
$ impfuna           <chr> "Algo parecido a mi", "Parecido a mi", "Parecido a m…
$ impenva           <chr> "Parecido a mi", "Muy parecido a mi", "Muy parecido …
$ age_group         <fct> 3a Edad, Juventud, Madurez, 4a Edad, Madurez, Madure…
$ region            <fct> Centro Europa, Centro Europa, Centro Europa, Centro …
$ education_level   <fct> Medio, Alto, Alto, Alto, Medio, Alto, Medio, Alto, M…
$ wrclmch_segmented <fct> Alto, Alto, Alto, Alto, Alto, Alto, Medio, Alto, Baj…
$ ccrdprs_segmented <fct> Medio, Alto, Alto, Medio, Alto, Alto, Medio, Alto, B…

Page 1

Row

Edad media

52.1

Nivel de preocupación general por el cambio climático

Algo preocupado

Nivel de responsabilidad hacia la reducción del cambio climático

Medio

Row

Distribución por Género

Distribución por Nivel de Educación

Page 2

Row

Column

Creencia sobre la Causa del Cambio Climático y Nivel de Preocupación por el Cambio Climático

Creencia sobre la Causa del Cambio Climático y Nivel de Responsabilidad Personal para reducirlo

Row

Column

Creencia sobre las Causas del Cambio Climático y Grupos de Edad

Nivel de Responsabilidad Personal para reducir el cambio climático y Nivel de Educación

Page 3

Row

Column

Nivel de Responsabilidad Personal para reducir el cambio climático por Género

===================================== Row {data-height=50%} ————————————-

Column

Nivel de Responsabilidad Personal para reducir el cambio climático por país

Page 4

Row

Column

Importancia de Ser Rico y Nivel de Responsabilidad personal para reducir el cambio climático

### Igualdad y Oportunidades y Nivel de Responsabilidad personal para reducir el cambio climático

Row {data-height=50%} ————————————-

Column

Modestia y Nivel de Responsabilidad personal para reducir el cambio climático

### Modestia y Nivel de Responsabilidad personal para reducir el cambio climático

Row {data-height=50%} ————————————-

Column

Búsqueda de la diversión y Nivel de Responsabilidad personal para reducir el cambio climático

---
title: "Creencias, actitudes y valores hacia el cambio climático"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    vertical_layout: fill
    social: menu
    source_code: embed
---

```{r setup, include=FALSE}
# Establecer el espejo de CRAN
options(repos = c(CRAN = "https://cran.rstudio.com/"))

# Instalar y cargar librerías necesarias
if (!requireNamespace("flexdashboard", quietly = TRUE)) {
  install.packages("flexdashboard")
}
if (!requireNamespace("tidyverse", quietly = TRUE)) {
  install.packages("tidyverse")
}
if (!requireNamespace("plotly", quietly = TRUE)) {
  install.packages("plotly")
}
if (!requireNamespace("rnaturalearth", quietly = TRUE)) {
  install.packages("rnaturalearth")
}
if (!requireNamespace("rnaturalearthdata", quietly = TRUE)) {
  install.packages("rnaturalearthdata")
}
if (!requireNamespace("leaflet", quietly = TRUE)) {
  install.packages("leaflet")
}

library(flexdashboard)
library(tidyverse)
library(plotly)
library(rnaturalearth)
library(rnaturalearthdata)
library(leaflet)
library(dplyr)
library(sf)

# Ajustar opciones globales de knitr para suprimir mensajes y avisos
knitr::opts_chunk$set(
  message = FALSE,
  warning = FALSE
)

# Establecer el directorio de trabajo de forma persistente
knitr::opts_knit$set(root.dir = "C:/Users/Iuliu/Documents/PROYECTOCD")
```
```{r load-data}
# Leer el archivo CSV desde la subcarpeta '1_Datos'
datos <- read_csv("1_Datos/3_Datos_depurados.csv")

# Leer el archivo CSV desde la subcarpeta '1_Datos'
datos <- read_csv("1_Datos/3_Datos_depurados.csv", col_types = cols(
  cntry = col_character(),
  ccnthum = col_character(),
  ccrdprs = col_character(),
  wrclmch = col_character(),
  gndr = col_character(),
  agea = col_double(),
  eisced = col_character(),
  impricha = col_character(),
  ipeqopta = col_character(),
  ipmodsta = col_character(),
  impfuna = col_character(),
  impenva = col_character(),
  age_group = col_character(),
  region = col_character(),
  education_level = col_character(),
  wrclmch_segmented = col_character(),
  ccrdprs_segmented = col_character()
), show_col_types = FALSE)

# Convertir columnas a factores
datos <- datos %>%
  mutate(
    gndr = factor(gndr, levels = c("Hombre", "Mujer")),
    wrclmch_segmented = factor(wrclmch_segmented, levels = c("Bajo", "Medio", "Alto")),
    ccrdprs_segmented = factor(ccrdprs_segmented, levels = c("Bajo", "Medio", "Alto")),
    age_group = factor(age_group, levels = c("Juventud", "Juventud Adulta", "Adultez", "Madurez", "3a Edad", "4a Edad")),
    region = factor(region, levels = c("Nord Oeste", "Nord Este", "Nord Europa", "Centro Europa", "Sud Este")),
    education_level = factor(education_level, levels = c("Bajo", "Medio", "Alto"))
  )

# Filtrar datos eliminando la opción de "No creo que el cambio climatico este ocurriendo" y valores NA
filtered_data <- datos %>% 
  filter(ccnthum != "No creo que el cambio climatico este ocurriendo" & 
         !is.na(wrclmch_segmented) & 
         !is.na(ccrdprs_segmented) & 
         !is.na(age_group) & 
         !is.na(education_level) & 
         !is.na(gndr))

# Verificar la estructura de los datos
glimpse(datos)

```

Page 1
=====================================

Row {data-height=50}
-----------------------------------------------------------------------

### Edad media

```{r}
edad_media <- mean(datos$agea, na.rm = TRUE)
valueBox(round(edad_media, 1), "Media de Edad", icon = "fa-users", color = "#AFEEEE")
```
### Nivel de preocupación general por el cambio climático
```{r}
preocupacion_mas_frecuente <- names(sort(table(datos$wrclmch), decreasing = TRUE))[1]
valueBox(preocupacion_mas_frecuente, "Preocupación más frecuente por el cambio climático", icon = "fa-leaf", color = "#AFEEEE")
```
### Nivel de responsabilidad hacia la reducción del cambio climático
```{r}
responsabilidad_mas_frecuente <- names(sort(table(datos$ccrdprs_segmented), decreasing = TRUE))[1]
valueBox(responsabilidad_mas_frecuente, "Nivel de responsabilidad personal general para reducir el cambio climático", icon = "fa-hand-paper", color = "#AFEEEE")
```

Row {data-height=50}
-----------------------------------------------------------------------

### Distribución por Género


```{r}

data_genero <- datos %>%
  count(gndr) %>%
  mutate(percentage = n / sum(n) * 100)

plot_ly(data_genero, labels = ~gndr, values = ~percentage, type = 'pie', 
        textinfo = 'label+percent', insidetextorientation = 'radial',
        marker = list(colors = c('#B0C4DE', '#D8BFD8')))
```

### Distribución por Nivel de Educación

```{r}

data_educacion <- datos %>%
  count(education_level) %>%
  mutate(percentage = n / sum(n) * 100)

plot_ly(data_educacion, labels = ~education_level, values = ~percentage, type = 'pie', 
        textinfo = 'label+percent', insidetextorientation = 'radial',
        marker = list(colors = c('#ADD8E6', '#87CEFA', '#4682B4')))

```
Page 2
=====================================

Row {data-height=50%}
-------------------------------------

Column {data-width=50%}
-------------------------------------

### Creencia sobre la Causa del Cambio Climático y Nivel de Preocupación por el Cambio Climático

```{r}

filtered_data <- datos %>% 
  filter(ccnthum != "No creo que el cambio climatico este ocurriendo" & !is.na(wrclmch_segmented))


p1 <- ggplot(filtered_data, aes(x = ccnthum, fill = factor(wrclmch_segmented, levels = c("Bajo", "Medio", "Alto")))) +
  geom_bar(position = "stack", stat = "count") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1),
        plot.title = element_text(size = 20, face = "bold")) +  # Ajusta el tamaño y grosor del título
  labs(x = "Creencia sobre la Causa del Cambio Climatico", y = "Conteo", fill = "Nivel de Preocupación") +
  scale_fill_manual(values = c("Bajo" = "#a1dab4", "Medio" = "#41b6c4", "Alto" = "#2c7fb8"))

ggplotly(p1)


```


### Creencia sobre la Causa del Cambio Climático y Nivel de Responsabilidad Personal para reducirlo
```{r}

p2 <- ggplot(filtered_data, aes(x = ccnthum, fill = factor(ccrdprs_segmented, levels = c("Bajo", "Medio", "Alto")))) +
  geom_bar(position = "stack", stat = "count") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1),
        plot.title = element_text(size = 20, face = "bold")) +  # Ajusta el tamaño y grosor del título
  labs(x = "Creencias sobre la Causa del Cambio Climatico", y = "Conteo", fill = "Nivel de Responsabilidad") +
  scale_fill_manual(values = c("Bajo" = "#fbb4b9", "Medio" = "#f768a1", "Alto" = "#ae017e"))

ggplotly(p2)

```
Row {data-height=50%}
-------------------------------------

Column {data-width=50%}
-------------------------------------

### Creencia sobre las Causas del Cambio Climático y Grupos de Edad

```{r}
# Filtrar los datos para eliminar los NA en age_group y ccnthum
filtered_data <- filtered_data %>%
  filter(!is.na(age_group) & !is.na(ccnthum))

# Ordenar los niveles de la variable ccnthum para que la leyenda esté ordenada
filtered_data <- filtered_data %>%
  mutate(ccnthum = factor(ccnthum, levels = c("Completamente humano", "Principalmente humano", "Igualmente natural y humano", "Principalmente natural", "Procesos naturales")))

# Crear el gráfico interactivo con plotly
p3 <- ggplot(filtered_data, aes(x = age_group, fill = ccnthum)) +
  geom_bar(position = "stack", stat = "count") +
  theme_minimal() +
  theme(plot.title = element_text(size = 20, face = "bold"),
        axis.text.x = element_text(angle = 90, hjust = 1)) +  # Poner las etiquetas verticales
  labs(x = "Grupo de Edad", y = "Conteo", fill = "Creencia sobre la Causa del Cambio Climatico") +
  scale_fill_manual(values = c("Completamente humano" = "#d73027", 
                                "Principalmente humano" = "#fc8d59", 
                                "Igualmente natural y humano" = "#fee08b", 
                                "Principalmente natural" = "#d9ef8b", 
                                "Procesos naturales" = "#1a9850"))

ggplotly(p3)
```

### Nivel de Responsabilidad Personal para reducir el cambio climático y Nivel de Educación
```{r}

p4 <- ggplot(filtered_data, aes(x = education_level, fill = factor(ccrdprs_segmented, levels = c("Bajo", "Medio", "Alto")))) +
  geom_bar(position = "stack", stat = "count") +
  theme_minimal() +
  theme(plot.title = element_text(size = 20, face = "bold")) +  # Ajusta el tamaño y grosor del título
  labs(x = "Nivel de Educacion", y = "Conteo", fill = "Nivel de Responsabilidad") +
  scale_fill_manual(values = c("Bajo" = "#fbb4b9", "Medio" = "#f768a1", "Alto" = "#ae017e"))

ggplotly(p4)

```

Page 3
=====================================
Row {data-height=50%}
-------------------------------------

Column {data-width=50%}
-------------------------------------
### Nivel de Responsabilidad Personal para reducir el cambio climático por Género
```{r}

p5 <- ggplot(filtered_data, aes(x = gndr, fill = factor(ccrdprs_segmented, levels = c("Bajo", "Medio", "Alto")))) +
  geom_bar(position = "stack", stat = "count") +
  theme_minimal() +
  theme(plot.title = element_text(size = 20, face = "bold")) +  # Ajusta el tamaño y grosor del título
  labs(x = "Genero", y = "Conteo", fill = "Nivel de Responsabilidad") +
  scale_fill_manual(values = c("Bajo" = "#fbb4b9", "Medio" = "#f768a1", "Alto" = "#ae017e"))


ggplotly(p5)


```
=====================================
Row {data-height=50%}
-------------------------------------

Column {data-width=50%}
-------------------------------------
### Nivel de Responsabilidad Personal para reducir el cambio climático por país
```{r}

# Filtrar y preparar los datos
responsabilidad_pais <- datos %>%
  filter(!is.na(ccrdprs)) %>%
  group_by(cntry) %>%
  summarize(mean_responsibility = mean(as.numeric(ccrdprs), na.rm = TRUE))

# Obtener los datos geoespaciales de los países de Europa
europe <- ne_countries(continent = "Europe", scale = "medium", returnclass = "sf")

# Unir los datos de responsabilidad personal con los datos geoespaciales
europe_data <- left_join(europe, responsabilidad_pais, by = c("iso_a2" = "cntry"))

# Crear una paleta de colores personalizada
color_palette <- colorBin(palette = c("#fbb4b9", "#f768a1", "#ae017e"), domain = europe_data$mean_responsibility, bins = 5)

# Crear el mapa interactivo
leaflet(europe_data) %>%
  addTiles() %>%
  addPolygons(
    fillColor = ~color_palette(mean_responsibility),
    weight = 1,
    opacity = 1,
    color = "white",
    dashArray = "3",
    fillOpacity = 0.7,
    highlightOptions = highlightOptions(
      weight = 5,
      color = "#666",
      dashArray = "",
      fillOpacity = 0.7,
      bringToFront = TRUE
    ),
    label = ~paste(name, "<br>", "Responsabilidad: ", round(mean_responsibility, 2)),
    labelOptions = labelOptions(
      style = list("font-weight" = "normal", padding = "3px 8px"),
      textsize = "15px",
      direction = "auto"
    )
  ) %>%
  addLegend(
    pal = color_palette,
    values = ~mean_responsibility,
    opacity = 0.7,
    title = "Nivel de Responsabilidad",
    position = "bottomright"
  )

```

Page 4
=====================================

Row {data-height=50%}
-------------------------------------

Column {data-width=50%}
-------------------------------------

### Importancia de Ser Rico y Nivel de Responsabilidad personal para reducir el cambio climático

```{r}
 ggplot(filtered_data, aes(x = impricha, y = as.numeric(ccrdprs), fill = "Importancia de Ser Rico")) +
    geom_boxplot() +
    theme_minimal() +
    labs(x = "Importancia de Ser Rico", y = "Responsabilidad Personal") +
    scale_fill_manual(values = c("Importancia de Ser Rico" = "#FFD700")) +
    theme(axis.text.x = element_text(angle = 45, hjust = 1), 
          plot.title = element_text(size = 14, face = "bold"))
```
### Igualdad y Oportunidades y Nivel de Responsabilidad personal para reducir el cambio climático
```{r}
ggplot(filtered_data, aes(x = ipeqopta, y = as.numeric(ccrdprs), fill = "Igualdad y Oportunidades")) +
  geom_boxplot() +
  theme_minimal() +
  labs(x = "Igualdad y Oportunidades", y = "Responsabilidad Personal") +
  scale_fill_manual(values = c("Igualdad y Oportunidades" = "#1f78b4")) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1), 
        plot.title = element_text(size = 14, face = "bold"))


```
Row {data-height=50%}
-------------------------------------

Column {data-width=50%}
-------------------------------------
### Modestia y Nivel de Responsabilidad personal para reducir el cambio climático
```{r}
ggplot(filtered_data, aes(x = ipmodsta, y = as.numeric(ccrdprs), fill = "Modestia")) +
  geom_boxplot() +
  theme_minimal() +
  labs(x = "Modestia", y = "Responsabilidad Personal") +
  scale_fill_manual(values = c("Modestia" = "#dda0dd")) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1), 
        plot.title = element_text(size = 14, face = "bold"))

```
### Modestia y Nivel de Responsabilidad personal para reducir el cambio climático
```{r}

ggplot(filtered_data, aes(x = impfuna, y = as.numeric(ccrdprs), fill = "Cuidado del Medio Ambiente")) +
  geom_boxplot() +
  theme_minimal() +
  labs(x = "Cuidado del Medio Ambiente", y = "Responsabilidad Personal") +
  scale_fill_manual(values = c("Cuidado del Medio Ambiente" = "#66c2a5")) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1), 
        plot.title = element_text(size = 14, face = "bold"))

```
Row {data-height=50%}
-------------------------------------

Column {data-width=50%}
-------------------------------------
### Búsqueda de la diversión y Nivel de Responsabilidad personal para reducir el cambio climático

```{r}
ggplot(filtered_data, aes(x = impenva, y = as.numeric(ccrdprs), fill = "Búsqueda de Diversión")) +
  geom_boxplot() +
  theme_minimal() +
  labs(x = "Búsqueda de Diversión", y = "Responsabilidad Personal") +
  scale_fill_manual(values = c("Búsqueda de Diversión" = "#fb9a99")) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1), 
        plot.title = element_text(size = 14, face = "bold"))

```